<?php

namespace app\controller\wmapi\order;

use app\controller\wmapi\approvalsetting\ApproveSettingController;
use App\Library\Y;
use app\model\WaAdmins;
use app\model\WaApproveSetting;
use app\model\WaMembers;
use app\model\WaMonthlySettlement;
use app\model\WaOrders;
use app\model\WaOrdersPurchase;
use app\controller\wmapi\IndexController;
use app\controller\wmapi\PublicCommentController;
use app\model\WaOrdersPurchaseAmountDetail;
use app\model\WaOrdersPurchaseContract;
use app\model\WaOrdersPurchaseOperateLog;
use app\model\WaOrdersRelevance;
use app\model\WaOrdersPurchaseRelevance;
use app\model\WaPayrollRequisitionExamineApprove;
use app\model\WaPayrollRequisitionExamineApproveFlow;
use app\model\WaProducts;
use app\model\WaPurchasedVehicles;
use app\model\WaPurchasedVehiclesAmountDetail;
use app\model\WaPurchasedVehiclesRelevanceLog;
use app\model\WaPurchaseOrdersExamineApprove;
use app\model\WaPurchaseOrdersExamineApproveFlow;
use app\model\WaPurchasePayrollRequisition;
use app\model\WaSupplier;
use app\model\WaSupplierDomesticLogisticsFees;
use app\model\WaPurchasedVehiclesRelevance;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\controller\Crud;
use plugin\admin\app\model\User;
use support\Request;
use support\Response;
use Tinywan\Validate\Validate;
use Workerman\Worker;

class WaPurchasedVehiclesController extends Validate
{
    /*************************************************已采购车辆管理 - 国内物流*************************************************/


    /**
     * 1 采购订单确认配车->创建车辆集库待发运信息
     * @param Request $request
     */
    public function purchasedVehiclesCreate(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        \support\Db::beginTransaction();
        try {
            $need_add = []; // 需要创建的车架号
            //添加车架号确认日志
            if ($param['children_data']) {
                // 统计配车数量
                $add_count = 0;
                foreach ($param['children_data'] as $k) {

                    //  采购子订单信息
                    $purchase_children_data = WaOrdersPurchaseRelevance::find(['purchase_order_sn_child' => $k['purchase_order_sn_child']]);
                    $purchase_children_data = json_decode($purchase_children_data);
                    if (!$purchase_children_data) {
                        $data_error = [
                            '错误：获取不到采购子订单信息',
                            'purchase_order_sn_child：'.$k['purchase_order_sn_child'],
                        ];
                        IndexController::logErrorNew('purchasedVehiclesCreate', $data_error);
                        return IndexController::errored($purchase_children_data, '获取不到采购子订单信息');
                    }
                    // 获取该笔子订单有几辆车 需要几个车架号
                    $purchase_children_data->count;

                    //  采购主订单信息
                    $purchase_data = WaOrdersPurchase::find(['purchase_order_sn' => $purchase_children_data->purchase_order_sn_parent]);
                    $purchase_data = json_decode($purchase_data);
                    if (!$purchase_data) {
                        $data_error = [
                            '错误：获取不到采购订单信息',
                            'purchase_order_sn：'. $purchase_children_data->purchase_order_sn_parent,
                        ];
                        IndexController::logErrorNew('purchasedVehiclesCreate', $data_error);
                        return IndexController::errored($purchase_data, '获取不到采购订单信息');
                    }

                    // 删除 purchase_children_sn 的信息
//                    $del = WaPurchasedVehicles::delete(['purchase_children_sn' => $purchase_children_data->purchase_children_sn]);

                    $no_del = []; // 不用删除数据
                    foreach ($k['vins'] as $kv) {
                        //创建子订单配车信息
                        $purchased_vehicles = WaPurchasedVehicles::find(['vin' => $kv['vin']]);
                        $purchased_vehicles = json_decode($purchased_vehicles);
                        if ($purchased_vehicles) {
                            if ($purchased_vehicles->purchase_children_sn != $k['purchase_order_sn_child']) {
                                $data_error = [
                                    '错误：车架号已存在',
                                    '车架号：'. $purchased_vehicles->purchase_children_sn .'/'. $k['purchase_order_sn_child'],
                                ];
                                IndexController::logErrorNew('purchasedVehiclesCreate', $data_error);
                                return IndexController::errored($kv['vin'], '车架号已存在');
                            }
                        }
                        if (!$kv['vin']) {
                            $data_error = [
                                '错误：车架数据不能为空',
                                '车架号：'. $kv['vin'],
                            ];
                            IndexController::logErrorNew('purchasedVehiclesCreate', $data_error);
                            return IndexController::errored($kv, '数据不能为空');
                        }
                        // 已绑定销售订单的不能修改 / 单号已存在的不用删除 也不用修改  / 其它的 删除  / 再把新的单号添加进来
                        $count_num = 0;
                        $purchased_vehicles_check_data = WaPurchasedVehicles::all(['*'], ['purchase_children_sn' => $k['purchase_order_sn_child']]);
                        $purchased_vehicles_check_data = json_decode($purchased_vehicles_check_data);
                        if ($purchased_vehicles_check_data) {
                            foreach ($purchased_vehicles_check_data as $kc) {
                                if ($kc->sales_order_sn && $kc->confirm_status == 2) {
                                    if (!in_array($kc->vin, $no_del)) {
                                        array_push($no_del, $kc->vin); // 已绑定销售订单的不能修改
                                    }
                                    $count_num = $count_num + 1;
                                } elseif ($kv['vin'] == $kc->vin) {
                                    if (!in_array($kc->vin, $no_del)) {
                                        array_push($no_del, $kc->vin); // 单号已存在的不用删除 也不用修改
                                    }
                                    $count_num = $count_num + 1;
                                } else {
                                    if (!in_array($kv['vin'], $need_add)) {
                                        if (!in_array($kv['vin'], $no_del)) {
                                            array_push($need_add, $kv['vin']); // 再把新的单号添加进来
                                        }
                                    }
                                    $count_num = $count_num + 1;
                                }
                            }

                        } else {
                            if (!in_array($kv['vin'], $need_add)) {
                                if (!in_array($kv['vin'], $no_del)) {
                                    array_push($need_add, $kv['vin']); // 再把新的单号添加进来
                                }

                            }
                        }

                    }
                    // 删除多余旧的车架号数据
                    if ($no_del){
                        $purchased_vehicles_condition = [];
                        $purchased_vehicles_condition [] = ['purchase_children_sn', '=', $k['purchase_order_sn_child']];
                        WaPurchasedVehicles::deleteByVin($purchased_vehicles_condition, $no_del); // 可能已经删掉了重复删除就会不为真
                    }
                    // 获取需要创建的车架号
                    foreach ($k['vins'] as $kv) {
                        $add_count++;
                        if (in_array($kv['vin'], $need_add)) {

                            $purchased_vehicles_check = WaPurchasedVehicles::find(['vin' => $kv['vin']]);
                            $purchased_vehicles_check = json_decode($purchased_vehicles_check);
                            if (!$purchased_vehicles_check) {
                                $data = [
                                    'vin' => $kv['vin'], // 车架号vin码
                                    'purchase_order_sn' => $purchase_children_data->purchase_order_sn_parent,// 关联采购订单
                                    'sales_order_sn' => $purchase_children_data->order_sn_parent,// 关联销售订单
                                    'sales_children_sn' => $purchase_children_data->order_sn_child,// 关联销售子订单
                                    'purchase_children_sn' => $k['purchase_order_sn_child'],// 关联采购子订单
                                    'vehicle_status' => $purchase_children_data->vehicle_status, // 车辆状况(是否是新车)  1 新车 2 二手车

                                    'model' => $purchase_children_data->model,// 车型名称
                                    'brands_name' => $purchase_children_data->brands_name,// 品牌
                                    'car_type' => $purchase_children_data->car_type,// 汽车类型
                                    'series_name' => $purchase_children_data->series_name,// 车系名称
                                    'sub_brand_name' => $purchase_children_data->sub_brand_name,// 厂商
                                    'deposit_single_price' => $purchase_children_data->deposit_single_price,// 定金
                                    'purchase_single_quotation' => $purchase_children_data->purchase_single_quotation,// 采购单价

                                    'admin_id' => $adminId->id, // 创建人
                                    'admin_name' => $adminId->nickname, // 创建人名称
                                    'created_at' => dateTime(),
                                    'remark' => $kv['remark'],
                                    'status' => 1, // 1 集库存待发运

                                ];
                                if ($purchase_children_data->deposit_single_price) {
                                    $data['balance_single_price'] = round($purchase_children_data->purchase_single_quotation, 2) - round($purchase_children_data->deposit_single_price, 2);// 尾款

                                }
                                // 判断车辆供应商 的信息 来自 预录了  还是 定金选择
                                if ($purchase_children_data->supplier_id) {
                                    $supplier_id = $purchase_children_data->supplier_id;
                                } else {
                                    $supplier_id = $purchase_data->supplier_id;
                                }

                                $collection_shipment_wait_voucher = [
                                    'supplier_id' => $supplier_id,// 车辆供应商id
                                    'supplier_type' => 1,// 车辆供应商类型
                                    'admin_id' => $adminId->id, // 创建人
                                    'admin_name' => $adminId->nickname, // 创建人名称
                                    'confirm_time' => dateTime(),
                                    'created_at' => dateTime(),
                                ];

                                $data['collection_shipment_wait_voucher'] = json_encode($collection_shipment_wait_voucher);

                                $vin_add = WaPurchasedVehicles::created($data);
                                if (!$vin_add) {
                                    \support\Db::rollBack();

                                    return IndexController::errored('', '创建车辆集库待发运信息失败');
                                }

                                $data_relevance = [
                                    'vin' => $kv['vin'],
                                    'admin_id' => $adminId->id,
                                    'admin_name' => $adminId->nickname,
                                    'type' => 1,
                                    'created_at' => dateTime(),
                                    'confirm_time' => dateTime(),
                                ];
                                $vin_relevance_add = WaPurchasedVehiclesRelevance::created($data_relevance);
                                if (!$vin_relevance_add) {
                                    \support\Db::rollBack();
                                    $data_error = [
                                        '错误：创建集库发运关联信息存储失败',
                                        '车架号：'.$kv['vin'].'返回值'.$vin_relevance_add,
                                    ];
                                    IndexController::logErrorNew('purchasedVehiclesCreate', $data_error);
                                    return IndexController::errored('', '创建集库发运关联信息存储失败');
                                }


                                // 采购车辆操作日志
                                $data_log = [
                                    'vin' => $kv['vin'],
                                    'status' => 1,
                                    'describe' => '确认配车',
                                    'admin_id' => $adminId->id,
                                    'admin_name' => $adminId->nickname,
                                    'created_at' => dateTime(),
                                ];
                                $data_log_add = WaPurchasedVehiclesRelevanceLog::created($data_log);
                                if (!$data_log_add) {
                                    \support\Db::rollBack();
                                    $data_error = [
                                        '错误：创建车辆集库待发运信息失败操作日志添加错误',
                                        '车架号：'.$kv['vin'].'返回值'.$data_log_add,
                                    ];
                                    IndexController::logErrorNew('purchasedVehiclesCreate', $data_error);
                                    return IndexController::errored('', '创建车辆集库待发运信息失败操作日志添加错误');
                                }
                            }

                            // 同步采购子订单的费用明细 -> 车务的 车辆费用明细
                            // 获取采购订单的费用明细详情（都是单辆车费用明细）
//                            $purchase_amount_condition = [];
//                            $purchase_amount_condition [] = ['purchase_order_sn','=',$purchase_children_data->purchase_order_sn_parent];
//                            $purchase_amount_detail = WaOrdersPurchaseAmountDetail::all($purchase_amount_condition);
//                            $purchase_amount_detail = json_decode($purchase_amount_detail);
//                            if ($purchase_amount_detail){
//                                foreach ($purchase_amount_detail as $kamount){
//                                    $data_by_balance = [
//                                        'vin' => $param['vin'], // 车架号
//                                        'price_name' => $kamount->price_name, // 费用名称
//                                        'total_price' => $kamount->total_amount, // 每辆车尾款费用
//                                        'currency' => 1, // 货币类型   1人民币 2美元
//                                        'vehicles_type' => 1, // 车务类型 1 采购车务 2 跟单车务
//                                        'payment_type' => 1, // 支付方式  1 现结 2 月结
//                                        'payment_status' => 0, // 付款类型  0 待请款 1审批中 2 未付款 3 已付款 4 审核不通过 5 撤回 6 删除
////                                        'supplier_id' => $param['supplier_id'],
////                                        'supplier_type' => 1, //
////                                        'supplier_type_name' => '车辆供应商', //
////                                        'supplier_name' => $supplier->name,
//                                        'admin_id' => $adminId->id,
//                                        'admin_name' => $adminId->nickname,
//                                        'created_at' => dateTime(),
//                                    ];
//
//                                    $res_by_balance_add = WaPurchasedVehiclesAmountDetail::created($data_by_balance);
//                                    if (!$res_by_balance_add) {
//
//                                        return IndexController::successed('', '车辆尾款费用明细添加失败');
//                                    }
//                                }
//                            }


                        }
                    }

                    // 该采购订单需要配的车辆总数
                    $where_purchase_count = [];
                    $where_purchase_count [] = ['purchase_order_sn_parent', '=', $purchase_children_data->purchase_order_sn_parent];
                    $where_purchase_count [] = ['status', '!=', 7];

                    $count_by_relevance = WaOrdersPurchaseRelevance::countPur($where_purchase_count);

                    // 从入库中查出已配车的采购订单数量
                    $where_vehicles_count = [];
                    $where_vehicles_count [] = ['purchase_order_sn', '=', $purchase_children_data->purchase_order_sn_parent];
                    $where_vehicles_count [] = ['vehicle_status', '!=', 7];

                    $count_by_vehicles = WaPurchasedVehicles::count($where_vehicles_count);

//                    $count_by_relevance = json_decode($count_by_relevance);
                    // 小心这边统计的只是一个子订单的配车数量 不是整个采购订单的配车数量
                    //采购订单子订单车辆总数  == 该订单车库配车总数
                    if (intval($count_by_relevance) == intval($count_by_vehicles)) {
                        // 配车完成修改采购订单状态
                        PublicCommentController::采购订单状态;
                        $pur_status_condition = [];
                        $pur_status_condition [] = ['purchase_order_sn', '=', $purchase_children_data->purchase_order_sn_parent];
                        $pur_status_data = [
                            'purchase_orders_status' => 6,
                            'updated_at' => dateTime()
                        ];
                        $pur_up = WaOrdersPurchase::updated($pur_status_data, $pur_status_condition);
                        if(!$pur_up){
                            \support\Db::rollBack();
                            $data_error = [
                                '错误：已配车完成,采购订单待支付尾款状态修改失败',
                                '采购订单号：'.$purchase_children_data->purchase_order_sn_parent.'返回值'.$pur_up,
                            ];
                            IndexController::logErrorNew('purchasedVehiclesCreate', $data_error);

                            return IndexController::errored('', '已配车完成,采购订单待支付尾款状态修改失败');
                        }

//                        if ($purchase_children_data->order_sn_child){
//                            // 配车完成修改销售订单状态
//                            $sales_status_condition = [];
//                            $sales_status_condition [] = ['order_sn', '=', $purchase_children_data->order_sn_parent];
//                            $sales_status_data = [
//                                'status' => 19,
//                                'updated_at' => dateTime()
//                            ];
//                            $sale_up = WaOrders::updated($sales_status_data, $sales_status_condition);
//                            if ($sale_up){
//                                $data_error = [
//                                    '错误：配车完成修改销售订单状态失败',
//                                    '销售子订单号：'.$purchase_children_data->order_sn_parent.'返回值'.$pur_up,
//                                ];
//                                IndexController::logErrorNew('purchasedVehiclesCreate', $data_error);
//                            }
//                        }

                }


                }
            }
            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasedVehiclesCreate', $param, $adminId, $exception);

            return IndexController::errored($exception, '状态更新失败');
        }

    }

    /**
     * 2 集库发运（待验车入库）
     * @param Request $request
     */
    public function vehiclesCollectionShipping(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if (!array_key_exists('vin', $param)) {
            return IndexController::errored('', '车架号为必填');
        }
        if (!array_key_exists('collection_shipment_voucher', $param)) {
            return IndexController::errored('', '发运信息为必填');
        }
        if (!array_key_exists('supplier_id', $param['collection_shipment_voucher'])) {
            return IndexController::errored('', '供应商id为必填');
        }
        PublicCommentController::供应商类型;
        $param['collection_shipment_voucher']['supplier_type'] = 5; //
        \support\Db::beginTransaction();
        try {
            $purchased_vehicles_check = WaPurchasedVehicles::find(['vin' => $param['vin']]);
            $purchased_vehicles_check = json_decode($purchased_vehicles_check);
            if ($purchased_vehicles_check) {
                $collection_shipment_voucher = $param['collection_shipment_voucher'];
                // 遍历费用明细   发运     开票 上牌 转移 里面有费用 需要入库
                if ($collection_shipment_voucher) {
                    $more_can_data = [
                        'price_name' => '集库发运物流费',
                        'currency' => 1,// 1 人民币 2 美元 3 欧元
                        'adminId' => $adminId,
                        'param' => $param,
                        'voucher' => $collection_shipment_voucher,
                        'supplier_type' => 5,
                        'supplier_id' => $collection_shipment_voucher['supplier_id'],
                        'created_type' => 1, // 创建类型 1 自动 2 手动
                    ];
                    $addAmountDetailBack = WaPurchasedVehiclesController::addAmountDetail($more_can_data);
                    if ($addAmountDetailBack != 'true') {
                        return IndexController::errored('', $addAmountDetailBack);
                    }
                }


                $condition_up = [];
                $condition_up [] = ['vin', '=', $param['vin']];
                $condition_data = [
                    "collection_shipment_voucher" => json_encode($param['collection_shipment_voucher']),
                    'status' => 2,
                    "updated_at" => dateTime(),
                ];

                $result_up = WaPurchasedVehicles::updated($condition_up, $condition_data);
                if (!$result_up) {


                    return IndexController::errored('', '车辆集库发运失败');
                }
                $data_relevance = [
                    'vin' => $param['vin'],
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'type' => 2,
                    'created_at' => dateTime(),
                ];
                if ($param['collection_shipment_voucher']) {
                    $data_relevance['confirm_time'] = dateTime();
                }
                $result_relevance_add = WaPurchasedVehiclesRelevance::created($data_relevance);
                if (!$result_relevance_add) {


                    return IndexController::errored('', '集库发运关联信息存储败');
                }


                // 采购车辆操作日志
                $data_log = [
                    'vin' => $param['vin'],
                    'status' => 2,
                    'describe' => '集库发运',
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'created_at' => dateTime(),
                ];
                $data_log_add = WaPurchasedVehiclesRelevanceLog::created($data_log);
                if (!$data_log_add) {


                    return IndexController::errored('', '车辆待入库操作日志添加错误');
                }
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logError('vehiclesCollectionShipping', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }

    }

    /**
     * 3 验车入库（已入库待上牌）
     * 需要同步 定金 和 尾款 到车辆费用明细
     * @param Request $request
     */
    public function purchasedVehiclesConfirmWarehousing(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if (!array_key_exists('vin', $param)) {
            return IndexController::errored('', '车架号为必填');
        }
        if (!array_key_exists('warehousing_voucher', $param)) {
            return IndexController::errored('', '入库信息为必填');
        }

        $purchased_vehicles_check = WaPurchasedVehicles::find(['vin' => $param['vin']]);
        $purchased_vehicles_check = json_decode($purchased_vehicles_check);

        // 获取采购主订单信息
        $pur_condition = [];
        $pur_condition [] = ['purchase_order_sn', '=', $purchased_vehicles_check->purchase_order_sn];
        $pur_find = WaOrdersPurchase::find($pur_condition);
        $pur_find = json_decode($pur_find);
        if (!$pur_find) {


            return IndexController::errored('', '获取采购订单数据失败');
        }


        // 获取采购子订单(产品)的信息
        $pur_chi_condition = [];
        $pur_chi_condition [] = ['purchase_order_sn_child', '=', $purchased_vehicles_check->purchase_children_sn];
        $pur_chi_find = WaOrdersPurchaseRelevance::find($pur_chi_condition);
        $pur_chi_find = json_decode($pur_chi_find);
        if (!$pur_chi_find) {


            return IndexController::errored('', '获取采购订单产品数据失败');
        }

        \support\Db::beginTransaction();
        try {

            if ($purchased_vehicles_check) {

                $condition_up = [];
                $condition_up [] = ['vin', '=', $param['vin']];
                $condition_data = [
                    "warehousing_voucher" => json_encode($param['warehousing_voucher']),
                    'status' => 3,
                    "updated_at" => dateTime(),
                ];

                $result_up = WaPurchasedVehicles::updated($condition_up, $condition_data);
                if (!$result_up) {


                    return IndexController::errored('', '车辆集库发运失败');
                }


                $data_relevance = [
                    'vin' => $param['vin'],
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'type' => 3,
                    'created_at' => dateTime(),
                ];
                if ($param['warehousing_voucher']) {
                    $data_relevance['confirm_time'] = dateTime();
                }
                $result_relevance_add = WaPurchasedVehiclesRelevance::created($data_relevance);
                if (!$result_relevance_add) {


                    return IndexController::errored('', '集库发运关联信息存储败');
                }


                // 采购车辆操作日志
                $data_log = [
                    'vin' => $param['vin'],
                    'status' => 3,
                    'describe' => '验车入库',
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'created_at' => dateTime(),
                ];
                $data_log_add = WaPurchasedVehiclesRelevanceLog::created($data_log);
                if (!$data_log_add) {


                    return IndexController::errored('', '车辆待入库操作日志添加错误');
                }


                $supplier = IndexController::supplierDetailCommon(1, $pur_chi_find->supplier_id);
                $supplier = json_decode($supplier);
                if (!$supplier) {


                    return IndexController::errored('', '供应商信息获取失败');
                }


            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasedVehiclesConfirmWarehousing', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     * 4 确认上牌 (待开二手车票)
     * @param Request $request
     */
    public function purchasedVehiclesConfirmRegistration(Request $request)
    {
//        process($request);
        PublicCommentController::车辆状态;// 车辆状态
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if (!array_key_exists('vin', $param)) {
            return IndexController::errored('', '车架号为必填');
        }
        if (!array_key_exists('registration_voucher', $param)) {
            return IndexController::errored('', '确认上牌信息为必填');
        }
        if (!array_key_exists('supplier_id', $param['registration_voucher'])) {
            return IndexController::errored('', '供应商id为必填');
        }
        // 供应商类型： 1车辆供应商 2上牌供应商 3 国际货运代理 4保险供应商 5 国内物流
        $param['registration_voucher']['supplier_type'] = 2; //
        \support\Db::beginTransaction();
        try {
            $purchased_vehicles_check = WaPurchasedVehicles::find(['vin' => $param['vin']]);
            $purchased_vehicles_check = json_decode($purchased_vehicles_check);
            if ($purchased_vehicles_check) {
                $registration_voucher = $param['registration_voucher'];
                // 遍历费用明细   上牌    发运 开票 转移 里面有费用 需要入库
                PublicCommentController::供应商类型;
                if ($registration_voucher) {
                    $registration_voucher['total_price'] = $registration_voucher['registration_fee'];
                    $more_can_data = [
                        'price_name' => '上牌费用',
                        'currency' => 1,// 1 人民币 2 美元 3 欧元
                        'adminId' => $adminId,
                        'param' => $param,
                        'voucher' => $registration_voucher,
                        'supplier_type' => 2,
                        'supplier_id' => $registration_voucher['supplier_id'],
                        'created_type' => 1, // 创建类型 1 自动 2 手动
                    ];
                    $addAmountDetailBack = WaPurchasedVehiclesController::addAmountDetail($more_can_data);
                    if ($addAmountDetailBack != 'true') {
                        return IndexController::errored('', $addAmountDetailBack);
                    }
                }


                $condition_up = [];
                $condition_up [] = ['vin', '=', $param['vin']];
                $condition_data = [
                    "registration_voucher" => json_encode($param['registration_voucher']),
                    'status' => 4,
                    "updated_at" => dateTime(),
                ];

                $result_up = WaPurchasedVehicles::updated($condition_up, $condition_data);
                if (!$result_up) {


                    return IndexController::errored('', '车辆确认上牌失败');
                }


                $data_relevance = [
                    'vin' => $param['vin'],
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'type' => 4,
                    'created_at' => dateTime(),
                ];
                if ($param['registration_voucher']) {
                    $data_relevance['confirm_time'] = dateTime();
                }
                $result_relevance_add = WaPurchasedVehiclesRelevance::created($data_relevance);
                if (!$result_relevance_add) {


                    return IndexController::errored('', '集库发运关联信息存储败');
                }


                // 采购车辆操作日志
                $data_log = [
                    'vin' => $param['vin'],
                    'status' => 4,
                    'describe' => '确认上牌',
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'created_at' => dateTime(),
                ];
                $data_log_add = WaPurchasedVehiclesRelevanceLog::created($data_log);
                if (!$data_log_add) {


                    return IndexController::errored('', '车辆确认上牌操作日志添加错误');
                }
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasedVehiclesConfirmRegistration', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     * 5 已开二手票(待转移出口)
     * @param Request $request
     */
    public function purchasedVehiclesConfirmInvoicing(Request $request)
    {
//        process($request);
        PublicCommentController::车辆状态;// 车辆状态
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if (!array_key_exists('vin', $param)) {
            return IndexController::errored('', '车架号为必填');
        }
        if (!array_key_exists('supplier_id', $param['lnvoicing_voucher'])) {
            return IndexController::errored('', '供应商id为必填');
        }
        if (!array_key_exists('supplier_type', $param['lnvoicing_voucher'])) {
            return IndexController::errored('', '供应商类型为必填');
        }
        if (!array_key_exists('lnvoicing_voucher', $param)) {
            return IndexController::errored('', '二手车开票信息为必填');
        }

        \support\Db::beginTransaction();
        try {
            $purchased_vehicles_check = WaPurchasedVehicles::find(['vin' => $param['vin']]);
            $purchased_vehicles_check = json_decode($purchased_vehicles_check);
            if ($purchased_vehicles_check) {

                $lnvoicing_voucher = $param['lnvoicing_voucher'];
                // 遍历费用明细   开票    发运 上牌 转移 里面有费用 需要入库
                PublicCommentController::供应商类型;
                if ($lnvoicing_voucher) {
                    $lnvoicing_voucher['total_price'] = $lnvoicing_voucher['used_car_fee'];
                    $more_can_data = [
                        'price_name' => '二手车开票费用',
                        'currency' => 1,// 1 人民币 2 美元 3 欧元
                        'adminId' => $adminId,
                        'param' => $param,
                        'voucher' => $lnvoicing_voucher,
                        'supplier_type' => $lnvoicing_voucher['supplier_type'],
                        'supplier_id' => $lnvoicing_voucher['supplier_id'],
                        'created_type' => 1, // 创建类型 1 自动 2 手动
                    ];

                    $addAmountDetailBack = WaPurchasedVehiclesController::addAmountDetail($more_can_data);
                    if ($addAmountDetailBack != 'true') {
                        return IndexController::errored('', $addAmountDetailBack);
                    }
                }


                $condition_up = [];
                $condition_up [] = ['vin', '=', $param['vin']];
                $condition_data = [
                    "lnvoicing_voucher" => json_encode($param['lnvoicing_voucher']),
                    'status' => 5,
                    "updated_at" => dateTime(),
                ];

                $result_up = WaPurchasedVehicles::updated($condition_up, $condition_data);
                if (!$result_up) {


                    return IndexController::errored('', '二手车开票失败');
                }

                $data_relevance = [
                    'vin' => $param['vin'],
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'type' => 5,
                    'created_at' => dateTime(),
                ];
                if ($param['lnvoicing_voucher']) {
                    $data_relevance['confirm_time'] = dateTime();
                }
                $result_relevance_add = WaPurchasedVehiclesRelevance::created($data_relevance);
                if (!$result_relevance_add) {


                    return IndexController::errored('', '集库发运关联信息存储败');
                }


                // 采购车辆操作日志
                $data_log = [
                    'vin' => $param['vin'],
                    'status' => 5,
                    'describe' => '确认二手车开票',
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'created_at' => dateTime(),
                ];
                $data_log_add = WaPurchasedVehiclesRelevanceLog::created($data_log);
                if (!$data_log_add) {


                    return IndexController::errored('', '二手车开票操作日志添加错误');
                }
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasedVehiclesConfirmInvoicing', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }

    }

    /**
     * 6 确认转移出口(待注销)
     * @param Request $request
     */
    public function purchasedVehiclesConfirmTransferExport(Request $request)
    {
        //        process($request);
        PublicCommentController::车辆状态;// 车辆状态
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if (!array_key_exists('vin', $param)) {
            return IndexController::errored('', '车架号为必填');
        }
        if (!array_key_exists('transfer_export_voucher', $param)) {
            return IndexController::errored('', '确认转移出口信息为必填');
        }
        if (!array_key_exists('supplier_id', $param['transfer_export_voucher'])) {
            return IndexController::errored('', '供应商id为必填');
        }
        if (!array_key_exists('supplier_type', $param['transfer_export_voucher'])) {
            return IndexController::errored('', '供应商类型为必填');
        }
        \support\Db::beginTransaction();
        try {
            $purchased_vehicles_check = WaPurchasedVehicles::find(['vin' => $param['vin']]);
            $purchased_vehicles_check = json_decode($purchased_vehicles_check);
            if ($purchased_vehicles_check) {

                $transfer_export_voucher = $param['transfer_export_voucher'];
                // 遍历费用明细   转移    发运 上牌 开票 里面有费用 需要入库
                PublicCommentController::供应商类型;
                if ($transfer_export_voucher) {
                    $transfer_export_voucher['total_price'] = $transfer_export_voucher['transfer_export_fee'];
                    $more_can_data = [
                        'price_name' => '转移出口费用',
                        'currency' => 1,// 1 人民币 2 美元 3 欧元
                        'adminId' => $adminId,
                        'param' => $param,
                        'voucher' => $transfer_export_voucher,
                        'supplier_type' => $transfer_export_voucher['supplier_type'],
                        'supplier_id' => $transfer_export_voucher['supplier_id'],
                        'created_type' => 1, // 创建类型 1 自动 2 手动
                    ];

                    $addAmountDetailBack = WaPurchasedVehiclesController::addAmountDetail($more_can_data);
                    if ($addAmountDetailBack != 'true') {
                        return IndexController::errored('', $addAmountDetailBack);
                    }
                }


                $condition_up = [];
                $condition_up [] = ['vin', '=', $param['vin']];
                $condition_data = [
                    "transfer_export_voucher" => json_encode($param['transfer_export_voucher']),
                    'status' => 6,
                    "updated_at" => dateTime(),
                ];

                $result_up = WaPurchasedVehicles::updated($condition_up, $condition_data);
                if (!$result_up) {


                    return IndexController::errored('', '车辆确认转移出口失败');
                }

                $data_relevance = [
                    'vin' => $param['vin'],
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'type' => 6,
                    'created_at' => dateTime(),
                ];
                if ($param['transfer_export_voucher']) {
                    $data_relevance['confirm_time'] = dateTime();
                }
                $result_relevance_add = WaPurchasedVehiclesRelevance::created($data_relevance);
                if (!$result_relevance_add) {


                    return IndexController::errored('', '集库发运关联信息存储败');
                }

                // 采购车辆操作日志
                $data_log = [
                    'vin' => $param['vin'],
                    'status' => 6,
                    'describe' => '确认转移出口',
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'created_at' => dateTime(),
                ];
                $data_log_add = WaPurchasedVehiclesRelevanceLog::created($data_log);
                if (!$data_log_add) {


                    return IndexController::errored('', '车辆确认转移出口操作日志添加错误');
                }
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasedVehiclesConfirmTransferExport', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }

    }

    /**
     * 7 确认注销(待退保)
     * @param Request $request
     */
    public function purchasedVehiclesConfirmOff(Request $request)
    {
        //        process($request);
        PublicCommentController::车辆状态;// 车辆状态
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if (!array_key_exists('vin', $param)) {
            return IndexController::errored('', '车架号为必填');
        }
        if (!array_key_exists('off_voucher', $param)) {
            return IndexController::errored('', '确认注销信息为必填');
        }

        \support\Db::beginTransaction();
        try {
            $purchased_vehicles_check = WaPurchasedVehicles::find(['vin' => $param['vin']]);
            $purchased_vehicles_check = json_decode($purchased_vehicles_check);
            if ($purchased_vehicles_check) {

                $condition_up = [];
                $condition_up [] = ['vin', '=', $param['vin']];
                $condition_data = [
                    "off_voucher" => json_encode($param['off_voucher']),
                    'status' => 7,
                    "updated_at" => dateTime(),
                ];

                $result_up = WaPurchasedVehicles::updated($condition_up, $condition_data);
                if (!$result_up) {


                    return IndexController::errored('', '车辆确认注销失败');
                }

                $data_relevance = [
                    'vin' => $param['vin'],
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'type' => 7,
                    'created_at' => dateTime(),
                ];
                if ($param['off_voucher']) {
                    $data_relevance['confirm_time'] = dateTime();
                }
                $result_relevance_add = WaPurchasedVehiclesRelevance::created($data_relevance);
                if (!$result_relevance_add) {


                    return IndexController::errored('', '集库发运关联信息存储败');
                }

                // 采购车辆操作日志
                $data_log = [
                    'vin' => $param['vin'],
                    'status' => 7,
                    'describe' => '确认注销',
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'created_at' => dateTime(),
                ];
                $data_log_add = WaPurchasedVehiclesRelevanceLog::created($data_log);
                if (!$data_log_add) {


                    return IndexController::errored('', '车辆确认注销操作日志添加错误');
                }
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasedVehiclesConfirmOff', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     * 8 确认退保(待集港发运)
     * @param Request $request
     */
    public function purchasedVehiclesConfirmSurrender(Request $request)
    {
        //        process($request);
        PublicCommentController::车辆状态;// 车辆状态
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if (!array_key_exists('vin', $param)) {
            return IndexController::errored('', '车架号为必填');
        }
        if (!array_key_exists('surrender_voucher', $param)) {
            return IndexController::errored('', '确认退保信息为必填');
        }

        \support\Db::beginTransaction();
        try {
            $purchased_vehicles_check = WaPurchasedVehicles::find(['vin' => $param['vin']]);
            $purchased_vehicles_check = json_decode($purchased_vehicles_check);
            if ($purchased_vehicles_check) {

                $condition_up = [];
                $condition_up [] = ['vin', '=', $param['vin']];
                $condition_data = [
                    "surrender_voucher" => json_encode($param['surrender_voucher']),
                    'status' => 8,
                    "updated_at" => dateTime(),
                ];

                $result_up = WaPurchasedVehicles::updated($condition_up, $condition_data);
                if (!$result_up) {


                    return IndexController::errored('', '车辆确认退保失败');
                }

                $data_relevance = [
                    'vin' => $param['vin'],
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'type' => 8,
                    'created_at' => dateTime(),
                ];
                if ($param['surrender_voucher']) {
                    $data_relevance['confirm_time'] = dateTime();
                }
                $result_relevance_add = WaPurchasedVehiclesRelevance::created($data_relevance);
                if (!$result_relevance_add) {


                    return IndexController::errored('', '集库发运关联信息存储败');
                }


                // 采购车辆操作日志
                $data_log = [
                    'vin' => $param['vin'],
                    'status' => 8,
                    'describe' => '确认退保',
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'created_at' => dateTime(),
                ];
                $data_log_add = WaPurchasedVehiclesRelevanceLog::created($data_log);
                if (!$data_log_add) {


                    return IndexController::errored('', '车辆确认退保操作日志添加错误');
                }
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasedVehiclesConfirmSurrender', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }


    /*************************************************已采购车辆管理 - 国际物流*************************************************/

    /**
     * 9 确认订舱(待报关)
     * booking_space_voucher 9 订舱凭证
     * @param Request $request
     */
    public function purchasedVehiclesConfirmBookingSpace(Request $request)
    {
        //        process($request);
        PublicCommentController::车辆状态;// 车辆状态
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if (!array_key_exists('vin', $param)) {
            return IndexController::errored('', '车架号为必填');
        }
        if (!array_key_exists('booking_space_voucher', $param)) {
            return IndexController::errored('', '确认订舱信息为必填');
        }

        \support\Db::beginTransaction();
        try {
            $purchased_vehicles_check = WaPurchasedVehicles::find(['vin' => $param['vin']]);
            $purchased_vehicles_check = json_decode($purchased_vehicles_check);
            if ($purchased_vehicles_check) {

                $booking_space_voucher = $param['booking_space_voucher'];
                PublicCommentController::供应商类型;
                // 遍历费用明细   发运     开票 上牌 转移 里面有费用 需要入库
                if ($booking_space_voucher) {
                    $booking_space_voucher['total_price'] = $booking_space_voucher['inter_fee'];
                    $param['booking_space_voucher']['supplier_type'] = 3;
                    $inter_currency = $booking_space_voucher['inter_currency'];
                    $more_can_data = [
                        'price_name' => '确认订舱-国际货运费用',
                        'currency' => $inter_currency,// 1 人民币 2 美元 3 欧元
                        'adminId' => $adminId,
                        'param' => $param,
                        'voucher' => $booking_space_voucher,
                        'supplier_type' => $param['booking_space_voucher']['supplier_type'],
                        'supplier_id' => $booking_space_voucher['supplier_id'],
                        'created_type' => 1, // 创建类型 1 自动 2 手动
                    ];
                    $addAmountDetailBack = WaPurchasedVehiclesController::addAmountDetail($more_can_data);
                    if ($addAmountDetailBack != 'true') {
                        return IndexController::errored('', $addAmountDetailBack);
                    }

                    $booking_space_voucher['total_price'] = $booking_space_voucher['ground_fee'];
                    $ground_currency = $booking_space_voucher['ground_currency'];
                    $more_can_data = [
                        'price_name' => '确认订舱-地面入港费用',
                        'currency' => $ground_currency,// 1 人民币 2 美元 3 欧元
                        'adminId' => $adminId,
                        'param' => $param,
                        'voucher' => $booking_space_voucher,
                        'supplier_type' => $param['booking_space_voucher']['supplier_type'],
                        'supplier_id' => $booking_space_voucher['supplier_id'],
                        'created_type' => 1, // 创建类型 1 自动 2 手动
                    ];
                    $addAmountDetailBack = WaPurchasedVehiclesController::addAmountDetail($more_can_data);
                    if ($addAmountDetailBack != 'true') {
                        return IndexController::errored('', $addAmountDetailBack);
                    }

                }


                $condition_up = [];
                $condition_up [] = ['vin', '=', $param['vin']];
                $condition_data = [
                    "booking_space_voucher" => json_encode($param['booking_space_voucher']),
                    'status' => 9,
                    "updated_at" => dateTime(),
                ];

                $result_up = WaPurchasedVehicles::updated($condition_up, $condition_data);
                if (!$result_up) {


                    return IndexController::errored('', '车辆确认订舱失败');
                }

                // 采购车辆操作日志
                $data_log = [
                    'vin' => $param['vin'],
                    'status' => 9,
                    'describe' => '确认订舱',
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'created_at' => dateTime(),
                ];
                $data_log_add = WaPurchasedVehiclesRelevanceLog::created($data_log);
                if (!$data_log_add) {


                    return IndexController::errored('', '车辆确认订舱操作日志添加错误');
                }
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasedVehiclesConfirmBookingSpace', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     * 10 确认报关(待装运)
     * declare_customs_voucher  10 报关凭证
     * @param Request $request
     */
    public function purchasedVehiclesConfirmDeclareCustoms(Request $request)
    {
        //        process($request);
        PublicCommentController::车辆状态;// 车辆状态
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if (!array_key_exists('vin', $param)) {
            return IndexController::errored('', '车架号为必填');
        }
        if (!array_key_exists('declare_customs_voucher', $param)) {
            return IndexController::errored('', '确认报关信息为必填');
        }

        \support\Db::beginTransaction();
        try {
            $purchased_vehicles_check = WaPurchasedVehicles::find(['vin' => $param['vin']]);
            $purchased_vehicles_check = json_decode($purchased_vehicles_check);
            if ($purchased_vehicles_check) {


                $declare_customs_voucher = $param['declare_customs_voucher'];
                PublicCommentController::供应商类型;
                // 遍历费用明细   发运     开票 上牌 转移 里面有费用 需要入库
                if ($declare_customs_voucher) {
                    $declare_customs_voucher['total_price'] = $declare_customs_voucher['declare_customs_fee'];
                    $currency = $declare_customs_voucher['currency'];
                    $more_can_data = [
                        'price_name' => '报关费用',
                        'currency' => $currency,// 1 人民币 2 美元 3 欧元
                        'adminId' => $adminId,
                        'param' => $param,
                        'voucher' => $declare_customs_voucher,
                        'supplier_type' => 3,
                        'supplier_id' => $declare_customs_voucher['supplier_id'],
                        'created_type' => 1, // 创建类型 1 自动 2 手动
                    ];

                    $addAmountDetailBack = WaPurchasedVehiclesController::addAmountDetail($more_can_data);
                    if ($addAmountDetailBack != 'true') {
                        return IndexController::errored('', $addAmountDetailBack);
                    }
                }


                $condition_up = [];
                $condition_up [] = ['vin', '=', $param['vin']];
                $condition_data = [
                    "declare_customs_voucher" => json_encode($param['declare_customs_voucher']),
                    'status' => 10,
                    "updated_at" => dateTime(),
                ];

                $result_up = WaPurchasedVehicles::updated($condition_up, $condition_data);
                if (!$result_up) {


                    return IndexController::errored('', '车辆确认报关失败');
                }

                // 采购车辆操作日志
                $data_log = [
                    'vin' => $param['vin'],
                    'status' => 10,
                    'describe' => '确认报关',
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'created_at' => dateTime(),
                ];
                $data_log_add = WaPurchasedVehiclesRelevanceLog::created($data_log);
                if (!$data_log_add) {


                    return IndexController::errored('', '车辆确认报关操作日志添加错误');
                }
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasedVehiclesConfirmDeclareCustoms', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     * 11 确认装运(待提单释放)
     * shipment_voucher  11 装运凭证
     * @param Request $request
     */
    public function purchasedVehiclesConfirmShipment(Request $request)
    {
        //        process($request);
        PublicCommentController::车辆状态;// 车辆状态
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if (!array_key_exists('vin', $param)) {
            return IndexController::errored('', '车架号为必填');
        }
        if (!array_key_exists('shipment_voucher', $param)) {
            return IndexController::errored('', '确认装运信息为必填');
        }

        \support\Db::beginTransaction();
        try {
            $purchased_vehicles_check = WaPurchasedVehicles::find(['vin' => $param['vin']]);
            $purchased_vehicles_check = json_decode($purchased_vehicles_check);
            if ($purchased_vehicles_check) {


                $shipment_voucher = $param['shipment_voucher'];
                PublicCommentController::供应商类型;
                // 遍历费用明细   发运     开票 上牌 转移 里面有费用 需要入库
                if ($shipment_voucher) {
                    $shipment_voucher['total_price'] = $shipment_voucher['shipment_fee'];
                    $currency = $shipment_voucher['currency'];

                    $more_can_data = [
                        'price_name' => '装运费用',
                        'currency' => $currency,// 1 人民币 2 美元 3 欧元
                        'adminId' => $adminId,
                        'param' => $param,
                        'voucher' => $shipment_voucher,
                        'supplier_type' => 3,
                        'supplier_id' => $shipment_voucher['supplier_id'],
                        'created_type' => 1, // 创建类型 1 自动 2 手动
                    ];

                    $addAmountDetailBack = WaPurchasedVehiclesController::addAmountDetail($more_can_data);
                    if ($addAmountDetailBack != 'true') {
                        return IndexController::errored('', $addAmountDetailBack);
                    }
                }


                $condition_up = [];
                $condition_up [] = ['vin', '=', $param['vin']];
                $condition_data = [
                    "shipment_voucher" => json_encode($param['shipment_voucher']),
                    'status' => 11,
                    "updated_at" => dateTime(),
                ];

                $result_up = WaPurchasedVehicles::updated($condition_up, $condition_data);
                if (!$result_up) {


                    return IndexController::errored('', '车辆确认装运失败');
                }

                // 采购车辆操作日志
                $data_log = [
                    'vin' => $param['vin'],
                    'status' => 11,
                    'describe' => '确认装运',
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'created_at' => dateTime(),
                ];
                $data_log_add = WaPurchasedVehiclesRelevanceLog::created($data_log);
                if (!$data_log_add) {


                    return IndexController::errored('', '车辆确认装运操作日志添加错误');
                }
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasedVehiclesConfirmShipment', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }


    /**
     * 12 确认提单释放(待结关)
     * release_bill_lading_voucher   12 提单释放凭证
     * @param Request $request
     */
    public function purchasedVehiclesConfirmReleaseBillLading(Request $request)
    {
        //        process($request);
        PublicCommentController::车辆状态;// 车辆状态
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if (!array_key_exists('vin', $param)) {
            return IndexController::errored('', '车架号为必填');
        }
        if (!array_key_exists('release_bill_lading_voucher', $param)) {
            return IndexController::errored('', '确认提单释放信息为必填');
        }

        \support\Db::beginTransaction();
        try {
            $purchased_vehicles_check = WaPurchasedVehicles::find(['vin' => $param['vin']]);
            $purchased_vehicles_check = json_decode($purchased_vehicles_check);
            if ($purchased_vehicles_check) {

                $condition_up = [];
                $condition_up [] = ['vin', '=', $param['vin']];
                $condition_data = [
                    "release_bill_lading_voucher" => json_encode($param['release_bill_lading_voucher']),
                    'status' => 12,
                    "updated_at" => dateTime(),
                ];

                $result_up = WaPurchasedVehicles::updated($condition_up, $condition_data);
                if (!$result_up) {


                    return IndexController::errored('', '车辆确认提单释放失败');
                }

                // 采购车辆操作日志
                $data_log = [
                    'vin' => $param['vin'],
                    'status' => 12,
                    'describe' => '确认提单释放',
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'created_at' => dateTime(),
                ];
                $data_log_add = WaPurchasedVehiclesRelevanceLog::created($data_log);
                if (!$data_log_add) {


                    return IndexController::errored('', '车辆确认提单释放操作日志添加错误');
                }
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasedVehiclesConfirmReleaseBillLading', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     * 13 确认结关(待退税)
     * customs_clearance_voucher 13 结关凭证
     * @param Request $request
     */
    public function purchasedVehiclesConfirmCustomsClearance(Request $request)
    {
        //        process($request);
        PublicCommentController::车辆状态;// 车辆状态
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if (!array_key_exists('vin', $param)) {
            return IndexController::errored('', '车架号为必填');
        }
        if (!array_key_exists('customs_clearance_voucher', $param)) {
            return IndexController::errored('', '确认结关发运信息为必填');
        }

        \support\Db::beginTransaction();
        try {
            $purchased_vehicles_check = WaPurchasedVehicles::find(['vin' => $param['vin']]);
            $purchased_vehicles_check = json_decode($purchased_vehicles_check);
            if ($purchased_vehicles_check) {

                $condition_up = [];
                $condition_up [] = ['vin', '=', $param['vin']];
                $condition_data = [
                    "customs_clearance_voucher" => json_encode($param['customs_clearance_voucher']),
                    'status' => 13,
                    "updated_at" => dateTime(),
                ];

                $result_up = WaPurchasedVehicles::updated($condition_up, $condition_data);
                if (!$result_up) {


                    return IndexController::errored('', '车辆确认结关失败');
                }

                // 采购车辆操作日志
                $data_log = [
                    'vin' => $param['vin'],
                    'status' => 13,
                    'describe' => '确认结关',
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'created_at' => dateTime(),
                ];
                $data_log_add = WaPurchasedVehiclesRelevanceLog::created($data_log);
                if (!$data_log_add) {


                    return IndexController::errored('', '车辆确认结关操作日志添加错误');
                }
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasedVehiclesConfirmCustomsClearance', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }


    /**
     * 14 确认退税(完成车务)
     * drawback_voucher  14 退税凭证
     * @param Request $request
     */
    public function purchasedVehiclesConfirmDrawback(Request $request)
    {


        PublicCommentController::车辆状态;// 车辆状态
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if (!array_key_exists('vin', $param)) {
            return IndexController::errored('', '车架号为必填');
        }
        if (!array_key_exists('drawback_voucher', $param)) {
            return IndexController::errored('', '确认退税信息为必填');
        }

        \support\Db::beginTransaction();
        try {
            $purchased_vehicles_check = WaPurchasedVehicles::find(['vin' => $param['vin']]);
            $purchased_vehicles_check = json_decode($purchased_vehicles_check);

            if ($purchased_vehicles_check) {

                $condition_up = [];
                $condition_up [] = ['vin', '=', $param['vin']];
                $condition_data = [
                    "drawback_voucher" => json_encode($param['drawback_voucher']),
                    'status' => 14,
                    "updated_at" => dateTime(),
                ];

                $result_up = WaPurchasedVehicles::updated($condition_up, $condition_data);
                if (!$result_up) {


                    return IndexController::errored('', '车辆确认退税失败');
                }

                // 采购车辆操作日志
                $data_log = [
                    'vin' => $param['vin'],
                    'status' => 14,
                    'describe' => '确认退税',
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'created_at' => dateTime(),
                ];
                $data_log_add = WaPurchasedVehiclesRelevanceLog::created($data_log);
                if (!$data_log_add) {


                    return IndexController::errored('', '车辆确认退税操作日志添加错误');
                }

                /**
                 * 这个操作是 单辆车 处理退税 -> 需要该笔订单下的 所有 产品都 配完车 且 是最后一个车 完成退税时  才能完成销售订单
                 *  如何判定当前操作是最后一辆车完成退税
                 * 1.得先获取当前订单销售订单的所有 子订单信息
                 * 2.遍历子订单 查询车辆库存表判断是否已入库 和 入库数量
                 * 3.如果所有子订单 都已配车 且 每辆车都已 完成退税(除了当前车架号) 修改订单状态为 已完成
                 */
                if ($purchased_vehicles_check->sales_order_sn) {
                    $result_up = WaPurchasedVehiclesController::syncSalesByVehiclesStatus($purchased_vehicles_check->sales_order_sn, $param['vin']);
                    if ($result_up != 'true') {
                        return IndexController::errored($result_up, '销售订单状态同步失败');
                    }
                }

            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasedVehiclesConfirmDrawback', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }


    public static function syncSalesByVehiclesStatus($sales_order_sn, $vin)
    {
        // 获取所有订单的子订单信息
        $sales_children_condition = [];
        $sales_children_condition [] = ['order_sn_parent', '=', $sales_order_sn];
        $sales_children_data = WaOrdersRelevance::all($sales_children_condition);
        $sales_children_data = json_decode($sales_children_data);
        if ($sales_children_condition) {
            $is_vin_over = 2; // 1 未完成  2 已完成
            // 遍历子订单 查询车辆库存表判断是否配车和 配车数量
            foreach ($sales_children_data as $ksc) {
                // 获取子订单数量车型数量 和已配车数量
                if ($ksc->count == $ksc->vin_count) {

                    // 配车完成 -> 判断是否都完成退税
                        $vehicles_condition = ['sales_children_sn' => $ksc->order_sn_child];
                        $vehicles_field = ['*'];
                        $vehicles_data = WaPurchasedVehicles::all($vehicles_field, $vehicles_condition);
                        $vehicles_data = json_decode($vehicles_data);
                        if ($vehicles_data) {
                            foreach ($vehicles_data as $kv) {
                                PublicCommentController::车辆状态;
                                // 判断是否完成退税 完成车务
                                if ($kv->status != 14) {
                                        //退税完成操作是 需要排除当前退税车辆
                                        if ($kv->vin != $vin) {
                                            // 退税未完成
                                            $is_vin_over = 101; // 1 未完成  2 已完成
                                            break;
                                        }
                                }
                            }
                        } else {
                            // 获取子订单 车辆信息失败
                            $is_vin_over = 103; // 1 未完成  2 已完成
                            break;
                        }

                } else {
                    // 该笔订单配车未完成
                    $is_vin_over = 104; // 1 未完成  2 已完成
                    break;
                }
            }
        } else {
            // 获取子订单信息失败
            $is_vin_over = 105; // 1 未完成  2 已完成
        }
        // 车辆都配车完成后  修改销售订单为已完成 跟单中
        PublicCommentController::销售订单状态;
        if ($is_vin_over == 2) {
            $sales_condition = [];
            $sales_condition [] = ['order_sn', '=', $sales_order_sn];

            $sales_data = WaOrders::find($sales_condition);
            $sales_data = json_decode($sales_data);
            if ($sales_data) {
                if ($sales_data->status == 19) {
                    $condition_sales_order_up = [];
                    $condition_sales_order_up [] = ['order_sn', '=', $sales_order_sn];
                    $condition_sales_order_data = [
                        'status' => 9,
                        "updated_at" => dateTime(),
                    ];

                    $result_sales_order_up = WaOrders::updated($condition_sales_order_data, $condition_sales_order_up);
                    if (!$result_sales_order_up) {
                        return '销售订单完成状态修改失败';
                    }
                } else {
                    /**
                     *   请先联系业务员 处理 销售订单中的 配车 和 尾款  车务 和 订单 模块都是独立的 状态可以同步 但是不能关联限制
                     * 如果车辆完成所有的 车务 但是 销售订单 还未去完成尾款  不在跟单中状态 只能在完成请款时 同步确认车辆对应的  车务 来更新是否完成销售订单的状态
                     * 否则销售订单 对应的 尾款请款细节会被遗漏
                     */
                }


            } else {
               //  完成车务退税  车辆不一定要绑定销售订单    车务流程时单独的
            }
        }
        return 'true';
    }




    /*************************************************已采购车辆管理 - 列表*************************************************/

    /**
     * 已采购车辆入库 - 列表
     * @param Request $request
     */
    public function purchasedVehiclesList(Request $request)
    {
//        process($request);
        $param = $request->all();
        $fields = ['*'];
        $condition = [];
        $between = [];
        if ($param['purchase_order_sn']) {
            $condition [] = ['purchase_order_sn', 'like', '%' . $param['purchase_order_sn'] . '%'];
        }
        if ($param['sales_order_sn']) {
            $condition [] = ['sales_order_sn', 'like', '%' . $param['sales_order_sn'] . '%'];
        }
        if ($param['supplier_name']) {
            // 默认 车辆供应商
            $condition [] = ['ve.vehicle_supplier_name', 'like', '%' . $param['supplier_name'] . '%'];
        }
        if ($param['vin']) {
            $condition [] = ['ve.vin', 'like', '%' . $param['vin'] . '%'];
        }
        if ($param['admin_name']) {
            $condition [] = ['ve.admin_name', 'like', '%' . $param['admin_name'] . '%'];
        }
        if ($param['status']) {
            $condition [] = ['ve.status', '=', $param['status']];
        }
        if ($param['type']) {
            $condition [] = ['rel.type', '=', $param['type']];
        } else {
            $condition [] = ['rel.type', '=', 1];
        }


        if ($param['start_time'] && $param['end_time']) {
            $between [] = [$param['start_time'], $param['end_time']];
        }

        $page = page($param['page']);
        $pageNum = pageNum($param['pageNum']);
        $fields = ['ve.*', 'rel.type as rel_status', 'rel.confirm_time'];
        $rule = WaPurchasedVehicles::list($page, $pageNum, $fields, $condition, $between);

        return IndexController::successed($rule, '已采购车辆入库列表');
    }

    /**
     * 已采购车辆入库 详情（所有）
     * @param Request $request
     */
    public function purchasedVehiclesDetail(Request $request)
    {
//        process($request);
        $param = $request->all();
        $condition = [];
        if ($param['vin']) {
            $condition [] = ['vin', '=', $param['vin']];
        } else {
            return IndexController::errored('', '车架号不能为空');
        }

        $rule = WaPurchasedVehicles::find($condition);

        return IndexController::successed($rule, '已采购车辆国内入库详情信息');
    }

    /**
     * 已采购车辆入库 - 国内详情
     * @param Request $request
     */
    public function purchasedDomesticVehiclesDetail(Request $request)
    {
//        process($request);
        $param = $request->all();
        $condition = [];
        if ($param['vin']) {
            $condition [] = ['vin', '=', $param['vin']];
        } else {
            return IndexController::errored('', '车架号不能为空');
        }

        $rule = WaPurchasedVehicles::domesticFind($condition);

        return IndexController::successed($rule, '已采购车辆国内入库详情信息');
    }

    /**
     * 已采购车辆入库 - 国际详情
     * @param Request $request
     */
    public function purchasedInterVehiclesDetail(Request $request)
    {
//        process($request);
        $param = $request->all();
        $condition = [];
        if ($param['vin']) {
            $condition [] = ['vin', '=', $param['vin']];
        } else {
            return IndexController::errored('', '车架号不能为空');
        }

        $rule = WaPurchasedVehicles::interFind($condition);

        return IndexController::successed($rule, '已采购车辆国际入库详情信息');
    }


    /**
     * 确认订舱-凭证获取-地面入港费用
     */
    public function vehiclesByGroundCostDetail(Request $request)
    {
//        process($request);
        $param = $request->all();
        $condition = [];
        if ($param['vin']) {
            $condition [] = ['vin', '=', $param['vin']];
        } else {
            return IndexController::errored('', '车架号不能为空');
        }

        $vehicles = WaPurchasedVehicles::find($condition);
        $vehicles = json_decode($vehicles);
        if ($vehicles) {
            $booking_space_voucher = $vehicles->booking_space_voucher;
            $ground_cost_detail = $booking_space_voucher->ground_cost_detail;
            if (!$ground_cost_detail) {
                return IndexController::errored('', '获取失败，未找到相关图片');
            } else {
                $ground_cost_detail = json_encode($ground_cost_detail);
                return IndexController::successed($ground_cost_detail, '地面入港费用');

            }
        } else {
            return IndexController::errored('', '获取失败，未找到相关图片');
        }

    }

    /**
     * 确认订舱-凭证获取-国际货运费用
     */
    public function vehiclesByInterCostDetail(Request $request)
    {
//        process($request);
        $param = $request->all();
        $condition = [];
        if ($param['vin']) {
            $condition [] = ['vin', '=', $param['vin']];
        } else {
            return IndexController::errored('', '车架号不能为空');
        }

        $vehicles = WaPurchasedVehicles::find($condition);
        $vehicles = json_decode($vehicles);
        if ($vehicles) {
            $booking_space_voucher = $vehicles->booking_space_voucher;
            $inter_cost_detail = $booking_space_voucher->inter_cost_detail;
            if (!$inter_cost_detail) {
                return IndexController::errored('', '获取失败，未找到相关图片');
            } else {
                $inter_cost_detail = json_encode($inter_cost_detail);
                return IndexController::successed($inter_cost_detail, '国际货运费用');

            }
        } else {
            return IndexController::errored('', '获取失败，未找到相关图片');
        }

    }

    /**
     * 确认提单释放-凭证获取-尾款外汇支付水单
     */
    public function vehiclesByBalanceForeignExchangeReceiptDetail(Request $request)
    {
//        process($request);
        $param = $request->all();
        $condition = [];
        if ($param['vin']) {
            $condition [] = ['vin', '=', $param['vin']];
        } else {
            return IndexController::errored('', '车架号不能为空');
        }
        $condition [] = ['price_name', '=', '尾款外汇支付水单'];
        $vehicles = WaPurchasePayrollRequisition::find($condition);
        $vehicles = json_decode($vehicles);
        if ($vehicles) {
            $payment_voucher = $vehicles->payment_voucher;
            if ($payment_voucher) {
                $payment_voucher = json_encode($payment_voucher);
                return IndexController::successed($payment_voucher, '尾款外汇支付水单');
            } else {
                return IndexController::errored('', '获取失败，未找到相关图片');
            }

        } else {
            return IndexController::errored('', '获取失败，未找到相关图片');
        }

    }

    /*************************************************已采购车辆管理 - 其它*************************************************/

    /**
     * 已采购车辆列表不分页 - 已入库/未配车
     * @param Request $request
     */
    public function purchasedVehiclesListAll(Request $request)
    {
//        process($request);
        $param = $request->all();
        $condition = [];
        PublicCommentController::车辆配车状态;
        PublicCommentController::车辆状态;
        $order_sn_child = $param['order_sn_child'];
        if ($order_sn_child) {
            $order_condition = [];
            $order_condition [] = ['order_sn_child', '=', $order_sn_child];
            $order_data = WaOrdersRelevance::find($order_condition);
            $order_data = json_decode($order_data);
            if (!$order_data) {
                return IndexController::errored('', '获取销售订单产品数据失败');
            }
            $condition [] = ['brands_name', '=', $order_data->brands_name]; // 品牌
            $condition [] = ['series_name', '=', $order_data->series_name]; // 车系
            $condition [] = ['model', '=', $order_data->model]; // 车型
        }


        $between = [3, 4, 5, 6];
//        $condition [] = ['vehicles.sales_order_sn', '=', $param['sales_order_sn']];
        $condition [] = ['vehicles.confirm_status', '=', 1]; // 是否被销售订单确认  1未确认(默认)  2 已确认
        //  通过销售订单中的产品编号筛选出未配配车的 入库车辆信息
        $res = WaPurchasedVehicles::findany($condition, $between);

        return IndexController::successed($res, '已采购车辆列表不分页 - 已入库/未配车');
    }

    /**
     * 采购订单车辆入库列表-产品采购数据
     * @param Request $request
     */
    public function purchasedVehiclesByPurChild(Request $request)
    {
//        process($request);
        $param = $request->all();
        $condition = [];
        $condition [] = ['purchase_order_sn_parent', '=', $param['purchase_order_sn']];
        $res = WaOrdersPurchaseRelevance::all($condition);
        if ($res) {
            $res = json_decode($res);
            foreach ($res as $kpr) {
                $condi = [];
                $condi [] = ['purchase_children_sn', '=', $kpr->purchase_order_sn_child];
                $vehicles = WaPurchasedVehicles::all(['*'], $condi);
                if ($vehicles) {
                    $vehicles = json_decode($vehicles);
                    $kpr->vins = $vehicles;
                } else {
                    $kpr->vins = [];
                }
            }
        }

        return IndexController::successed(json_encode($res), '采购订单车辆入库列表');
    }

    /**
     * 采购车辆待入库 - 编辑（凭证）
     * @param Request $request
     */
    public function purchasedVehiclesEdit(Request $request)
    {

//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        \support\Db::beginTransaction();
        try {
            // 确认入库凭证
            if ($param['warehousing_voucher']) {
                $data = [
                    'voucher' => json_encode($param['warehousing_voucher']),
                    'updated_at' => dateTime()
                ];
                $condition = [];
                $condition [] = ['vin', '=', $param['vin']];
                $condition [] = ['status', '=', 2];

                WaPurchasedVehiclesRelevanceLog::updated($condition, $data);
            }
            // 确认上牌
            if ($param['registration_voucher']) {
                $data = [
                    'voucher' => json_encode($param['registration_voucher']),
                    'updated_at' => dateTime()
                ];
                $condition = [];
                $condition [] = ['vin', '=', $param['vin']];
                $condition [] = ['status', '=', 4];

                WaPurchasedVehiclesRelevanceLog::updated($condition, $data);
            }
            // 确认开票
            if ($param['lnvoicing_voucher']) {
                $data = [
                    'voucher' => json_encode($param['lnvoicing_voucher']),
                    'updated_at' => dateTime()
                ];
                $condition = [];
                $condition [] = ['vin', '=', $param['vin']];
                $condition [] = ['status', '=', 5];

                WaPurchasedVehiclesRelevanceLog::updated($condition, $data);
            }

            // 确认转移待出口
            if ($param['transfer_export_voucher']) {
                $data = [
                    'voucher' => json_encode($param['transfer_export_voucher']),
                    'updated_at' => dateTime()
                ];
                $condition = [];
                $condition [] = ['vin', '=', $param['vin']];
                $condition [] = ['status', '=', 6];

                WaPurchasedVehiclesRelevanceLog::updated($condition, $data);
            }

            // 确认注销
            if ($param['off_voucher']) {
                $data = [
                    'voucher' => json_encode($param['off_voucher']),
                    'updated_at' => dateTime()
                ];
                $condition = [];
                $condition [] = ['vin', '=', $param['vin']];
                $condition [] = ['status', '=', 7];

                WaPurchasedVehiclesRelevanceLog::updated($condition, $data);
            }
            $data_all = [
                'warehousing_voucher' => json_encode($param['warehousing_voucher']),
                'registration_voucher' => json_encode($param['registration_voucher']),
                'lnvoicing_voucher' => json_encode($param['lnvoicing_voucher']),
                'transfer_export_voucher' => json_encode($param['transfer_export_voucher']),
                'off_voucher' => json_encode($param['off_voucher']),
                'voucher' => json_encode($param['warehousing_voucher']),
                'updated_at' => dateTime()
            ];
            $condition_all = [];
            $condition_all [] = ['vin', '=', $param['vin']];

            WaPurchasedVehicles::updated($condition_all, $data_all);


            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasedVehiclesEdit', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     * 已采购车辆入库 -状态修改
     * @param Request $request
     */
    public function purchasedVehiclesStatus(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $condition = [];
        $data = [];
        if ($param['vin']) {
            $condition [] = ['vin', '=', $param['vin']];
        } else {
            return IndexController::errored('', '车架号不能为空');
        }
        if ($param['status']) {
            $data [] = ['status', '=', $param['status']];
        } else {
            return IndexController::errored('', '状态不能为空');
        }

        \support\Db::beginTransaction();
        try {
            $rule = WaPurchasedVehicles::updated($condition, $data);

            \support\Db::commit();
            return IndexController::successed($rule, '已采购车辆入库状态更新成功');
        } catch (\Throwable $exception) {

            IndexController::logError('purchasedVehiclesStatus', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }

    }

    /**
     * 作废 已采购车辆 - 待支付交强险
     * @param Request $request
     */
    public function purchasedTrafficInsurance(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if ($param['vin']) {
            $vin = WaPurchasedVehicles::find(['vin' => $param['vin']]);
            $vin = json_decode($vin);
            if (!$vin) {
                return IndexController::errored('', '找不到车辆入库信息');
            }
        } else {
            return IndexController::errored('', '车架号不能为空');
        }

        $purchase_relevance = WaOrdersPurchaseRelevance::find(['purchase_order_sn_child' => $vin->purchase_children_sn]);
        $purchase_relevance = json_decode($purchase_relevance);
        if (!$purchase_relevance) {
            return IndexController::errored('', '采购子订单信息获取失败');
        }
        $status = 3;// 待支付交强险
        // 采购车辆  待支付交强险  操作日志
        $data_log = [
            'vin' => $param['vin'],
            'status' => 3,
            'describe' => $param['vin'] . '待支付交强险',
            'admin_id' => $adminId->id,
            'admin_name' => $adminId->nickname,
            'created_at' => dateTime(),
        ];
        $data_log_add = WaPurchasedVehiclesRelevanceLog::created($data_log);
        if (!$data_log_add) {
            echo 'confirmCompletionProcurement 待支付交强险操作日志添加错误' . $data_log_add;
            return IndexController::errored('', '待支付交强险操作日志添加错误');
        }
        $data = [
            'status' => 3,
            'updated_at' => dateTime(),
        ];
        // 采购车辆状态修改为 待支付交强险
        $condition = [];
//        $condition [] = ['purchase_order_sn', '=', $vin->purchase_order_sn];
        $condition [] = ['vin', '=', $param['vin']];
        $up_vehicles_status = WaPurchasedVehicles::updated($condition, $data);
        if (!$up_vehicles_status) {
            echo ' 待支付交强险状态修改失败' . $up_vehicles_status;
            return IndexController::errored('', '待支付交强险状态修改失败');
        }

        PublicCommentController::车辆状态;// 车辆状态
        // 判断购置税  是否新能源 car_type 1轿车 2 SUV 3 MPV 4 跑车 5新能源
        if (intval($purchase_relevance->car_type) == 5 && $purchase_relevance->purchase_tax == 0) {
            $status = 4;

            $data_purchase = [
                'status' => $status,
                'updated_at' => dateTime(),
            ];
            // 采购车辆状态修改为 待上牌
            $up_vehicles_status_second = WaPurchasedVehicles::updated($condition, $data_purchase);
            if (!$up_vehicles_status_second) {
                echo ' 待上牌状态修改失败' . $up_vehicles_status_second;
                return IndexController::errored('', '待上牌状态修改失败');
            }
            // 采购车辆  待上牌  操作日志
            $data_log = [
                'status' => $status,
                'vin' => $param['vin'], // 车架号
                'describe' => $param['vin'] . '修改状态为待上牌',
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'created_at' => dateTime(),
            ];
            $data_log_add = WaPurchasedVehiclesRelevanceLog::created($data_log);
            if (!$data_log_add) {
                echo 'confirmCompletionProcurement 待上牌操作日志添加错误' . $data_log_add;
                return IndexController::errored('', '待上牌操作日志添加错误');
            }
        }

        return IndexController::successed('', '已采购车辆入库状态更新成功');
    }



    /*************************************************车辆费用明细***************************************************/

    /*
   * 车辆费用明细添加
   */
    public function vinAmountDetailCreated(Request $request)
    {
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if (!array_key_exists('vin', $param)) {
            return IndexController::errored('', '车架号为必填');
        }

        if (!array_key_exists('price_name', $param)) {
            return IndexController::errored('', '款项名称');
        }

        if (!array_key_exists('supplier_id', $param)) {
            return IndexController::errored('', '供应商id为必填');
        }

        if (!array_key_exists('supplier_type', $param)) {
            return IndexController::errored('', '供应商类型为必填');
        }
        if (!array_key_exists('currency', $param)) {
            return IndexController::errored('', '币种为必填');
        }
        PublicCommentController::供应商类型;
        \support\Db::beginTransaction();
        try {
            $purchased_vehicles_check = WaPurchasedVehicles::find(['vin' => $param['vin']]);
            $purchased_vehicles_check = json_decode($purchased_vehicles_check);
            if ($purchased_vehicles_check) {
                $price_name = $param['price_name'];
                $total_price = [
                    'total_price' => $param['total_price']
                ];
                $currency = $param['currency'];

                $more_can_data = [
                    'price_name' => $price_name,
                    'currency' => $currency,// 1 人民币 2 美元 3 欧元
                    'adminId' => $adminId,
                    'param' => $param,
                    'voucher' => $total_price,
                    'supplier_type' => $param['supplier_type'],
                    'supplier_id' => $param['supplier_id'],
                    'created_type' => 2, // 创建类型 1 自动 2 手动
                ];


                $addAmountDetailBack = WaPurchasedVehiclesController::addAmountDetail($more_can_data);
                if ($addAmountDetailBack != 'true') {
                    return IndexController::errored('', $addAmountDetailBack);
                }
            }

            \support\Db::commit();
            return IndexController::successed('', '车辆费用明细添加成功');
        } catch (\Throwable $exception) {

            IndexController::logError('vinAmountDetailCreated', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '车辆费用明细添加失败');
        }
    }

    /**
     * 车辆费用明细列表
     * @param Request $request
     */
    public function vinAmountDetailList(Request $request)
    {
//        process($request);
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        $pva_condition = [];
        if ($param['vin']) {
            $pva_condition [] = ['vin', '=', $param['vin']];
        }
        // 获取车辆信息
        $vehicle_condition = [];
        $vehicle_condition [] = ['vin', '=', $param['vin']];
        $vehicle_data = WaPurchasedVehicles::find($vehicle_condition);
        $vehicle_data = json_decode($vehicle_data);
        if (!$vehicle_data){
            return IndexController::successed(json_encode($vehicle_data), '车辆信息获取失败');
        }

        // 获取车辆的采购订单费用明细
        if ($vehicle_data->vin){
            $purchased_amount_condition = [];
            $purchased_amount_condition [] = ['vin', '=', $vehicle_data->vin];
            $purchased_amount_data = WaPurchasedVehiclesAmountDetail::all($purchased_amount_condition,$adminId);
            $purchased_amount_data = json_decode($purchased_amount_data);
            if (!$purchased_amount_data){
                return IndexController::successed(json_encode($vehicle_data), '车辆对的的采购订单费用明细获取失败');
            }
        }

        // 获取车辆费用明细
        $pva_condition [] = ['payment_status', '<', 5];
        $pva = WaPurchasedVehiclesAmountDetail::all($pva_condition, $adminId);
        $pva = json_decode($pva);
        if ($pva){
            //把每个车辆对应的采购订单的明细 添加到 当前车辆的费用明细数组中
        }


        $pv_condition = [];
        if ($param['vin']) {
            $pv_condition [] = ['vin', '=', $param['vin']];
        }
//        $pv_condition [] = ['payment_status', '<', 5];
        $field = ['vin', 'brands_name', 'car_type', 'series_name', 'model', 'sub_brand_name',
            'purchase_order_sn', 'sales_order_sn', 'purchase_children_sn', 'sales_children_sn', 'brands_name', 'vehicle_status',];
        $pv = WaPurchasedVehicles::findByColumnName($field, $pv_condition);
        $pv = json_decode($pv);

        $res = [
            'vehicles_amount_detail' => $pva,
            'vehicles_detail' => $pv,
            'vehicles_total_price' => WaPurchasedVehiclesAmountDetail::sumsByTotalPrice($pv_condition),// 费用合计
            'vehicles_requested_price' => WaPurchasedVehiclesAmountDetail::sumsByRequestedPrice($pv_condition),// 已请款总额
            'vehicles_un_settlement' => WaPurchasedVehiclesAmountDetail::sumsByUnSettlement($pv_condition),// 未结算总额
            'vehicles_already_settlement' => WaPurchasedVehiclesAmountDetail::sumsByAlreadySettlement($pv_condition),// 已结算总额
        ];


        return IndexController::successed(json_encode($res), '车辆费用明细列表');
    }

    /**
     * 车辆费用明细详情删除
     * @param Request $request
     * @return Response
     */
    public function addAmountDetailDeletedById(Request $request)
    {
        //        process($request);
        $param = $request->all();
        $condition = [];
        if ($param['amount_id']) {
            $condition [] = ['id', '=', $param['amount_id']];
        }
        // 只有待请款才能删除
        // 付款类型  0 待请款 1审批中 2 未付款 3 已付款 4 审核不通过 5 撤回 6 删除
        $find = WaPurchasedVehiclesAmountDetail::find($condition);
        $find = json_decode($find);
        if ($find->payment_status != 0) {
            return IndexController::errored('', '只有待请款才能删除');
        }
        $wpvad_del = WaPurchasedVehiclesAmountDetail::deleted($condition);
        if (!$wpvad_del) {
            return IndexController::errored('', '删除失败');
        }
        return IndexController::successed('', '删除成功');
    }

    /**
     * 费用完结
     * 功能逻辑
     * 6、费用清单页面有一个【费用完结】的按钮，点击后可以完结费用，完结费用的必须包含以下两个条件。
     * 6.1 车务状态必须为终极状态，否则无法完结。由于终极状态尚未被定义出来，所以现结端一定是无法完结的。具体后面需求会提到。
     * 6.2 费用清单里面包含的所有现结付款的状态为已付款并且所有关联月结账单的请款状态为已付款
     * @param Request $request
     */
    public function addAmountDetailDomplete(Request $request)
    {

        //process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 判断请款
        PublicCommentController::请款单状态;
        $condition_by_payroll = [];
        $condition_by_payroll [] = ['vin', '=', $param['vin']];
        $condition_by_payroll [] = ['status', '<', 2];
        $find_by_payroll = WaPayrollRequisitionExamineApprove::find($adminId, $condition_by_payroll);
        if (json_decode($find_by_payroll)) {
//            $find_by_payroll = json_decode($find_by_payroll);
            return IndexController::errored('', '还有请款审批单未完成');
        }

        // 判断月结
        PublicCommentController::月结订单结算状态;
        $condition_by_month = [];
        $condition_by_month [] = ['vin', '=', $param['vin']];
        $condition_by_month [] = ['settlement_sratus', '<', 3];
        $find_by_month = WaMonthlySettlement::find($condition_by_month);
        if (!json_decode($find_by_month)) {
            return IndexController::errored('', '还有月结结算未完成');
        }

        // 判断明细中的结款状态
        PublicCommentController::车辆明细付款类型;
        $condition_by_amount = [];
        $condition_by_amount [] = ['vin', '=', $param['vin']];
        $between = [1, 2];
        $find_by_amount = WaPurchasedVehiclesAmountDetail::findByPaymentStatusBetween($condition_by_amount, $between);
        if (json_decode($find_by_amount)) {
            return IndexController::errored('', '车辆明细还有款项未结清');
        }

        // 判断车辆明细中是否有费用 额度
        PublicCommentController::车辆状态;
        $condition_by_vehicle = [];
        $condition_by_vehicle [] = ['vin', '=', $param['vin']];
        $find_by_vehicle = WaPurchasedVehiclesAmountDetail::all($condition_by_vehicle, $adminId);
        $find_by_vehicle = json_decode($find_by_vehicle);
        foreach ($find_by_vehicle as $kv) {
            if ($kv->requested_price) {
                if ($kv->requested_price <= $kv->total_price) {
                    return IndexController::errored($kv->price_name, '车辆明细还有款项待请款');
                }
            }
        }

        // 是否判断费用类目(即 固定类目 为必须有的费用类目 )


        try {
            // 车辆管理列表中的费用完结状态修改
            PublicCommentController::车辆状态;
            $condition_by_vehicle = [];
            $condition_by_vehicle [] = ['vin', '=', $param['vin']];
            $up_vehicle_status_data = [
                'status' => 20,
                'updated_at' => dateTime(),
            ];
            WaPurchasedVehicles::updated($condition_by_vehicle, $up_vehicle_status_data);

            \support\Db::commit();
            return IndexController::successed('', '费用完结状态修改成功');
        } catch (\Throwable $exception) {

            IndexController::logError('addAmountDetailDomplete', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '费用完结状态更新失败');
        }


    }

    public static function addAmountDetail($more_can_data)
    {
        $supplier_type = $more_can_data['supplier_type'];
        $supplier_id = $more_can_data['supplier_id'];
        $voucher = $more_can_data['voucher'];
        $param = $more_can_data['param'];
        $price_name = $more_can_data['price_name'];
        $adminId = $more_can_data['adminId'];
        $currency = $more_can_data['currency'];

        $supplier = IndexController::supplierDetailCommon($supplier_type, $supplier_id);
        $supplier = json_decode($supplier);
        if (!$supplier) {
            return '供应商信息获取失败';
        }
        PublicCommentController::供应商类型;
//                if ($supplier_type == 1) {
//                    $supplier_type_name = '车辆供应商';
//                } elseif ($supplier_type == 2) {
//                    $supplier_type_name = '上牌供应商';
//                } elseif ($supplier_type == 3) {
//                    $supplier_type_name = '国际货运代理';
//                } elseif ($supplier_type == 4) {
//                    $supplier_type_name = '保险供应商';
//                } elseif ($supplier_type == 5) {
//                    $supplier_type_name = '国内物流';
//                } else {
//                    $supplier_type_name = '';
//                }
        $supplier_type_name = IndexController::supplierTypeNameCommon($supplier_type);

        if (array_key_exists('total_price', $voucher)) {
            if ($voucher['total_price']) {
//                                foreach ($other_price as $ko){
                $pvc_data = [
                    'vin' => $param['vin'], // 车架号
                    'price_name' => $price_name, // 费用名称
                    'total_price' => round($voucher['total_price'], 2), // 车务费用
                    'currency' => $currency, // 货币类型   1人民币 2美元
                    'vehicles_type' => 1, // 车务类型 1 采购车务 2 跟单车务
                    'payment_type' => 1, // 支付方式  1 现结 2 月结
                    'payment_status' => 0, // 付款类型  0 待请款 1审批中 2 未付款 3 已付款 4 审核不通过 5 撤回 6 删除
                    'supplier_id' => $supplier_id,
                    'supplier_type' => $supplier_type, // 发运是 物流供应商
                    'supplier_type_name' => $supplier_type_name, // 发运是 物流供应商
                    'supplier_name' => $supplier->name,
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'created_type' => $more_can_data['created_type'],
                    'created_at' => dateTime(),

                ];
                $pvc_condition = [];
                $pvc_condition [] = ['vin', '=', $pvc_data['vin']];
                $pvc_condition [] = ['price_name', '=', $pvc_data['price_name']];
                $pvc_find = WaPurchasedVehiclesAmountDetail::find($pvc_condition);
                $pvc_find = json_decode($pvc_find);
                if ($pvc_find) {
                    // 先判断是否有请款  有的话 不能更新
                    $prea_condition = [];
                    $prea_condition [] = ['vin', '=', $pvc_data['vin']];
                    $prea_condition [] = ['price_name', '=', $pvc_data['price_name']];
                    $prea_condition [] = ['status', '<', 3]; // 状态 0 审批中 1 通过 2 驳回 3撤回
                    $prea_find = WaPayrollRequisitionExamineApprove::find($adminId, $pvc_condition);
                    $prea_find = json_decode($prea_find);
                    if ($prea_find) {
                        return '已有请款无法修改信息';
                    } else {
                        // 删除多余旧数据
                        WaPurchasedVehiclesAmountDetail::deleted($pvc_condition);
                    }

                }
                $pvc_add = WaPurchasedVehiclesAmountDetail::created($pvc_data);
                if (!$pvc_add) {
                    return '集库发运费用明细创建失败';
                }

            }
        }

        return 'true';
    }


}